<?php
/**
 * Created by PhpStorm.
 * User: XT
 * Date: 2017/4/17
 * Time: 15:58
 */
namespace core;

use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;

class DB extends Capsule {

    protected static $connections = [];

    /**
     * @param string $method
     * @param array $parameters
     * @return mixed
     */
    public static function __callStatic($method, $parameters)
    {
        // 自动初始化数据库
        return parent::__callStatic($method, $parameters);
    }

    /**
     * @param string $dbConfigKey
     * @return bool|\Illuminate\Database\Connection
     * @throws Exception
     */
    public static function connect($dbConfigKey = '')
    {
        $key = md5($dbConfigKey . '_db');
        if (isset(self::$connections[$key])) return self::$connections[$key];

        $dbConfig = Config::get('DB');
        $config = $dbConfigKey ? $dbConfig[$dbConfigKey] : $dbConfig['default'];
        $name = $dbConfigKey ? $dbConfigKey : 'default';

        if (is_null($config) || empty($config)) {
            throw new Exception('db config is wrong');
        }

        $capsule = new Capsule();

        $capsule->addConnection($config, $name);

        $capsule->setEventDispatcher(new Dispatcher(new Container));

        // Make this Capsule instance available globally via static methods... (optional)
        $capsule->setAsGlobal();

        // Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
        $capsule->bootEloquent();

        self::$connections[$key] = Capsule::connection($name);

        Capsule::connection($name)->enableQueryLog();//open queries sql log

        return self::$connections[$key];

    }
}
